# Copyright (c) 2025, zhn and contributors
# For license information, please see license.txt

import frappe
from frappe.model.document import Document


class HomeasySalesOrder(Document):
	def validate(self):
		"""验证订单数据"""
		# 确保订单号唯一
		if self.order_number:
			self.check_unique_order_number()
		
		# 确保日期逻辑正确
		if self.order_date and self.delivery_date:
			if self.delivery_date < self.order_date:
				frappe.throw("发货日期不能早于下单日期")
		
		# 设置创建时间和创建人
		if not self.creation_time:
			self.creation_time = frappe.utils.now()
		if not self.creator:
			self.creator = frappe.session.user
	
	def check_unique_order_number(self):
		"""检查订单号是否唯一"""
		if not self.order_number:
			return
			
		existing_order = frappe.db.exists("Homeasy Sales Order", {"order_number": self.order_number, "name": ["!=", self.name]})
		if existing_order:
			frappe.throw(f"订单号 {self.order_number} 已存在，请使用其他订单号")
	
	def on_update(self):
		"""更新时触发"""
		pass
	
	def on_submit(self):
		"""提交时触发"""
		# 更新订单状态为"生产中"
		if not self.order_status or self.order_status == "待处理":
			self.order_status = "生产中"
			self.db_set("order_status", self.order_status)
	
	def on_cancel(self):
		"""取消时触发"""
		# 更新订单状态为"已取消"
		self.db_set("order_status", "已取消")
